package com.gec.anan.driver.service.impl;

import com.gec.anan.common.execption.AnanException;
import com.gec.anan.common.result.ResultCodeEnum;
import com.gec.anan.driver.config.TencentCloudProperties;
import com.gec.anan.driver.service.CiService;
import com.gec.anan.driver.service.CosService;
import com.gec.anan.model.vo.driver.CosUploadVo;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpMethodName;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.*;
import com.qcloud.cos.region.Region;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.net.URL;
import java.util.Date;
import java.util.UUID;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class CosServiceImpl implements CosService {

    @Autowired
    private TencentCloudProperties properties;
    @Autowired
    private CiService ciService;
    //获取回显地址

    @Override
    public String getImageUrl(String path) {
        if(!StringUtils.hasText(path)) return "";
        //获取客户端
        COSClient client = getClient();
        //获取临时链接
        GeneratePresignedUrlRequest urlRequest = new GeneratePresignedUrlRequest(properties.getBucketPrivate(), path, HttpMethodName.GET);
        //设置获取临时请求时间 15分钟
        Date date = new DateTime().plusMinutes(15).toDate();
        urlRequest.setExpiration(date);
        //获取临时url
        URL url = client.generatePresignedUrl(urlRequest);
        //关闭客户端
        client.shutdown();
        return url.toString();
    }

    //获取上传客户端
    private COSClient getClient() {
        // 1 初始化用户身份信息（secretId, secretKey）。
        COSCredentials cred = new BasicCOSCredentials(properties.getSecretId(), properties.getSecretKey());
       // 2 设置 bucket 的地域, COS 地域的简称请参见 https://cloud.tencent.com/document/product/436/6224
       // clientConfig 中包含了设置 region, https(默认 http), 超时, 代理等 set 方法, 使用可参见源码或者常见问题 Java SDK 部分。
        Region region = new Region(properties.getRegion());
        ClientConfig clientConfig = new ClientConfig(region);
       // 这里建议设置使用 https 协议
       // 从 5.6.54 版本开始，默认使用了 https
        clientConfig.setHttpProtocol(HttpProtocol.https);
       // 3 生成 cos 客户端。
        COSClient cosClient = new COSClient(cred, clientConfig);
        return cosClient;
    }

    @Override
    @SneakyThrows
    public CosUploadVo upload(MultipartFile file, String path) {
        //获取客户端
        COSClient client = getClient();
        //上传文件元数据设置
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentLength(file.getSize());
        objectMetadata.setContentEncoding("UTF-8");
        objectMetadata.setContentType(file.getContentType());
        //截取文件名
        String fileType = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        //拼接新文件名
        String uploadPath = "/driver/"+path+"/"+ UUID.randomUUID().toString().replace("-", "")+fileType;
        //获取上传对象
        PutObjectRequest putObjectRequest = new PutObjectRequest(properties.getBucketPrivate(), uploadPath, file.getInputStream(), objectMetadata);
        //putObjectRequest.setStorageClass(StorageClass.Standard);
        PutObjectResult putObjectResult = client.putObject(putObjectRequest);
        log.info("上传成功返回结果{}",putObjectResult);
        //图片审核
        Boolean imagedAuditing = ciService.imageAuditing(uploadPath);
        if(!imagedAuditing){
            //删除违规图片
            client.deleteObject(properties.getBucketPrivate(), uploadPath);
            throw new AnanException(ResultCodeEnum.IMAGE_AUDITION_FAIL);
        }
        //关闭连接
        client.shutdown();
        //封装返回结果
        CosUploadVo cosUploadVo = new CosUploadVo();
        cosUploadVo.setUrl(uploadPath);
        //设置回显地址
        cosUploadVo.setShowUrl(getImageUrl(uploadPath));
        return cosUploadVo;
    }
}
